'use strict';


angular.module('cloap.services', [
    'ngResource'
])
    .factory('ActionLogger', function($resource) {
        return $resource("/cloap/admin/action_log/:id", {}, {});
    });



angular.module('cloap_app', [
    'ngSanitize', 'angular-websocket', 'ui.bootstrap', 'ui.router', 'ui.router.state', 'cloap.services'
])
    .config(function(WebSocketProvider) {
        WebSocketProvider
            .prefix('')
            .uri('ws://' + window.location.host + '/websocket');
    })
    .run(function($rootScope, $state, WebSocket) {
        $rootScope.cloap = {app_index: [], user: {}, admin_module: {}};
        $state.go("cloap");

        WebSocket.onmessage(function(event) {
            var response = JSON.parse(event.data);
            if (response.event == undefined) {
                // todo
            }
            else {
                if (response.data.result == 'error') {
                    $rootScope.cloap.error = response.event + ": " + response.data.message;
                }
                else {
                    $rootScope.$broadcast(response.event, response.data);
                }
            };
        });

        WebSocket.onopen(function() {
            $rootScope.cloap.websocket = {state: 'connected'};
        });

        WebSocket.onclose(function() {
            $rootScope.cloap.websocket = {state: 'disconnected'};
        });


        function waitForSocketConnected(send_call) {
            setTimeout(
                function(){
                    if (WebSocket.currentState() === 'OPEN') {
                        if(send_call !== undefined){
                            send_call();
                        }
                        return;
                    } else {
                        waitForSocketConnected(send_call);
                    }
                }, 5);
        };

        $rootScope.send = function(event, params) {
            $rootScope.cloap.error = '';
            waitForSocketConnected(function() {
                WebSocket.send(JSON.stringify({event: event, data: params}));
            });
        };

        $rootScope.remove_item = function(arr, item) {
            return _.filter(arr, function(e) { return e != item; });
        };



        $rootScope.$on('app.me', function(event, data) {
            $rootScope.cloap.app_index = _.filter(data, function(e) { return e.appid != 'admin'; });
            var admin = _.find(data, function(e) { return e.appid == 'admin'; });
            $rootScope.cloap.admin =  (admin != undefined);
        });

        $rootScope.$on('config.index', function(event, data) {
            $rootScope.cloap.config = {};
            for (var i in data) {
                var item = data[i];
                $rootScope.cloap.config[item.key] = item.value;
            };
        });

        $rootScope.$on('user.me', function(event, data) {
            console.log(data);
            console.log(data.login.length);
            $rootScope.cloap.user = data;
        });

        $rootScope.send('config.index', {});
        $rootScope.send('user.me', {});
    })

// =============================================================================
// 应用环境
// =============================================================================
    .config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state("cloap", {
                url: "/cloap",
                templateUrl: "/static/partial/cloap/index.html",
                controller: function($scope, $rootScope, $state) {
                    $scope.app_index = [];
                    $scope.$on('app.index', function(event, data) {
                        $scope.app_index = data;
                    });

                    $scope.switch_admin = function() {
                        $("#cloap_app_module .cloap_module").hide();
                        $state.go("setting.config");
                    };

                    $scope.$on('app.module', function(event, data) {
                        $rootScope.cloap.current_module = data.id;

                        var node = $("#cloap_app_module #" + data.id);
                        $("#cloap_app_module .cloap_module").hide();

                        if (node.length == 0) {
                            $("#cloap_app_module").append(data.homepage);
                        }
                        else {
                            node.show();
                        };
                    });
                }
            })
    })

// =============================================================================
// 系统设置
// =============================================================================
    .config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state("setting", {
                url: "/cloap/setting",
                templateUrl: "/static/partial/setting/index.html",
                controller: function($rootScope, $scope, $state) {
                    $scope.switch_dashboard = function() {
                        var mod = $rootScope.cloap.current_module;
                        if (mod != undefined) {
                            $("#cloap_app_module #" + mod).show();
                        };
                        $state.go("cloap");
                    };
                }
            })


        // --------------------------------------------------------------------------------
        // 操作日志
        // --------------------------------------------------------------------------------
            .state('setting.action_log', {
                url: '/cloap/setting/action_log',
                templateUrl: '/static/partial/setting/action_log/index.html',
                controller: function($rootScope, $scope, $state, ActionLogger) {
                    $rootScope.cloap.admin_module.current = 'action_log';
                    $scope.action_log_index = ActionLogger.query();
                }
            })
                    

        
        

            .state("setting.config", {
                url: "/config",
                templateUrl: "/static/partial/setting/config/index.html",
                controller: function($rootScope, $scope, $state) {
                    $rootScope.cloap.admin_module.current = 'config';

                    $scope.config_index = [];
                    $scope.$on('config.index', function(event, data) {
                        $scope.config_index = data;
                    });

                    $scope.$on('config.create', function(event, data) {
                        $rootScope.send('config.index', {});
                        $state.go("^");
                    });

                    $scope.$on('config.destroy', function(event, data) {
                        console.log(data);
                        if (data.result == "ok") {
                            $scope.config_index = _.filter($scope.config_index,
                                                           function(e) { return data.key !== e.key; });
                        };
                    });
                }
            })
            .state("setting.config.create", {
                url: "/create",
                templateUrl: "/static/partial/setting/config/create.html",
                controller: function($scope) {
                    $scope.config_new = {};
                    $scope.config_edit_sign = false;
                }
            })
            .state("setting.config.edit", {
                url: "/edit",
                templateUrl: "/static/partial/setting/config/create.html",
                params: {key: true, descr: true, value: true, mustbe: true},
                controller: function($scope, $state) {
                    console.log($state.params);
                    $scope.config_new = $state.params;
                    $scope.config_edit_sign = true;
                }
            })


            .state("setting.acl", {
                url: "/acl",
                templateUrl: "/static/partial/setting/acl/index.html",
                controller: function($rootScope, $scope, $state) {
                    $rootScope.cloap.admin_module.current = 'acl';

                    $scope.acl_index = [];
                    $scope.acl_options = ["allow", "deny"];

                    $scope.$on('acl.index', function(event, data) {
                        $scope.acl_index = data;
                    });

                    $scope.$on('acl.edit', function(event, data) {
                        _.each($scope.acl_index, function(e) { if (e.appid == data.appid) {e.editing = false; }});
                    });
                }
            })
            .state("setting.acl.edit", {
                url: "/edit",
                templateUrl: "/static/partial/setting/acl/edit.html",

            })


            .state("setting.app", {
                url: "/app",
                templateUrl: "/static/partial/setting/app/index.html",
                controller: function($rootScope, $scope, $state) {
                    $rootScope.cloap.admin_module.current = 'app';

                    $scope.app_index = [];
                    $scope.$on('app.index', function(event, data) {
                        $scope.app_index = _.filter(data, function(e) { return e.appid != 'admin'; });
                    });

                    $scope.$on('app.create', function(event, data) {
                        $scope.app_index.push(data);
                        $state.go("^");
                    });

                    $scope.$on('app.destroy', function(event, data) {
                        if (data.result == "ok") {
                            $scope.app_index = _.filter($scope.app_index,
                                                        function(e) { return data.id !== e.appid; });
                        };
                    });
                }
            })
            .state("setting.app.create", {
                url: "/create",
                templateUrl: "/static/partial/setting/app/create.html"
            })



            // 服务注册
            .state("setting.uddi", {
                url: "/uddi",
                templateUrl: "/static/partial/setting/uddi/index.html",
                controller: function($rootScope, $scope, $state) {
                    $rootScope.cloap.admin_module.current = 'uddi';

                    $scope.uddi_index = [];
                    $scope.$on('uddi.index', function(event, data) {
                        $scope.uddi_index = data;
                    });

                    $scope.$on('uddi.edit', function(event, data) {
                        _.each($scope.uddi_index, function(e) { if (e.appid == data.appid) {e.editing = false; }});
                    });
                }
            })





            .state("setting.organ", {
                abstract: true,
                url: "/organ",
                templateUrl: "/static/partial/setting/organ/index.html"
            })

        // --------------------------------------------------------------------------------
        // 组织机构 ———— 机构管理
        // --------------------------------------------------------------------------------
            .state("setting.organ.organ", {
                url: "/organ",
                templateUrl: "/static/partial/setting/organ/organ/index.html",
                controller: function($rootScope, $scope, $state) {
                    $rootScope.cloap.admin_module.current = 'organ';

                    $scope.organ_index = [];
                    $scope.$on('organ.index', function(event, data) {
                        $scope.organ_index = data;
                    });

                    $scope.$on('organ.create', function(event, data) {
                        $rootScope.send('organ.index', {});
                        $state.go("^");
                    });

                    $scope.$on('organ.destroy', function(event, data) {
                        $scope.organ_index =
                            _.filter($scope.organ_index,
                                     function(e) { return e.id != data.id; });
                    });
                }
            })
            .state("setting.organ.organ.create", {
                url: "/create",
                templateUrl: "/static/partial/setting/organ/organ/create.html",
                params: {id: true, name: true, assign: true},
                controller: function($rootScope, $scope, $state) {
                    $scope.organ_new = $state.params;

                    if ($scope.organ_new.id == undefined) {
                        $scope.organ_new = { assign: [] };
                    };

                    $scope.avail_member_index = [];
                    $scope.selected_member_index = [];

                    $scope.$on('user.index', function(event, data) {
                        $scope.selected_member_index = _.filter(data, function(e) { return _.contains($scope.organ_new.assign, e.dn); });
                        $scope.avail_member_index    = _.difference(data, $scope.selected_member_index);
                    });

                    $scope.create_command = function() {
                        $scope.organ_new.member = $scope.organ_new.assign;
                        $rootScope.send('organ.create', $scope.organ_new);
                    };

                    $scope.add_member = function(members, dn) {
                        var item = _.find($scope.avail_member_index, function(e) { return e.dn == dn; });
                        $scope.selected_member_index.push(item);
                        $scope.avail_member_index = _.without($scope.avail_member_index, item);
                        members.push(dn);
                        return members;
                    };

                    $scope.remove_member = function(members, item) {
                        $scope.avail_member_index.push(item);
                        $scope.selected_member_index = _.without($scope.selected_member_index, item);
                        return _.without(members, item.dn);
                    };
                }
            })

            .state("setting.organ.organ.edit", {
                url: "/edit",
                templateUrl: "/static/partial/setting/organ/organ/edit.html",
                params: {id: true, name: true, member: true},
                controller: function($scope, $state) {
                    $scope.organ_new = $state.params;
                }
            })

        // --------------------------------------------------------------------------------
        // 组织机构 ———— 类型管理
        // --------------------------------------------------------------------------------
            .state("setting.organ.rating", {
                url: "/rating",
                templateUrl: "/static/partial/setting/organ/rating/index.html",
                controller: function($rootScope, $scope, $state) {
                    $scope.rating_index = [];

                    $scope.$on('rating.index', function(event, data) {
                        $scope.rating_index = _.map(data, function(e) {
                            var v = e;
                            if (e.groups == undefined) { v.groups = []; };
                            if (e.positions == undefined) { v.positions = []; };
                            return v;
                        });
                    });

                    $scope.$on('rating.create', function(event, data) {
                        $rootScope.send('rating.index', {});
                        $state.go("^");
                    });

                    $scope.$on('rating.destroy', function(event, data) {
                        $scope.rating_index =
                            _.filter($scope.rating_index,
                                     function(e) { return e.id != data.id; });
                    });
                }
            })
            .state("setting.organ.rating.create", {
                url: "/create",
                templateUrl: "/static/partial/setting/organ/rating/create.html",
                params: {id: true, name: true, groups: true, positions: true, member: true},
                controller: function($rootScope, $scope, $state) {
                    $scope.rating_new = $state.params;

                    if ($scope.rating_new.id == undefined) {
                        $scope.rating_new = { groups: [], positions: [] };
                    };

                    $scope.avail_organ_index = [];
                    $scope.selected_organ_index = [];

                    $scope.avail_position_index = [];
                    $scope.selected_position_index = [];

                    $scope.$on('organ.index', function(event, data) {
                        $scope.selected_organ_index = _.filter(data, function(e) { return _.contains($scope.rating_new.groups, e.dn); });
                        $scope.avail_organ_index = _.difference(data, $scope.selected_organ_index);
                    });

                    $scope.$on('position.index', function(event, data) {
                        $scope.selected_position_index = _.filter(data, function(e) { return _.contains($scope.rating_new.positions, e.dn); });
                        $scope.avail_position_index = _.difference(data, $scope.selected_position_index);
                    });

                    $scope.create_command = function() {
                        $scope.rating_new.member = $scope.rating_new.groups.concat($scope.rating_new.positions);
                        $rootScope.send('rating.create', $scope.rating_new);
                    };

                    $scope.add_organ = function(members, dn) {
                        var item = _.find($scope.avail_organ_index, function(e) { return e.dn == dn; });
                        $scope.selected_organ_index.push(item);
                        $scope.avail_organ_index = _.without($scope.avail_organ_index, item);
                        members.push(dn);
                        return members;
                    };

                    $scope.remove_organ = function(members, item) {
                        $scope.avail_organ_index.push(item);
                        $scope.selected_organ_index = _.without($scope.selected_organ_index, item);
                        return _.without(members, item.dn);
                    };

                    $scope.add_position = function(members, dn) {
                        var item = _.find($scope.avail_position_index, function(e) { return e.dn == dn; });
                        $scope.selected_position_index.push(item);
                        $scope.avail_position_index = _.without($scope.avail_position_index, item);
                        members.push(dn);
                        return members;
                    };

                    $scope.remove_position = function(members, item) {
                        $scope.avail_position_index.push(item);
                        $scope.selected_position_index = _.without($scope.selected_position_index, item);
                        return _.without(members, item.dn);
                    };
                }
            })

        // --------------------------------------------------------------------------------
        // 组织机构 ———— 岗位管理
        // --------------------------------------------------------------------------------
            .state("setting.organ.position", {
                url: "/position",
                templateUrl: "/static/partial/setting/organ/position/index.html",
                controller: function($rootScope, $scope, $state) {
                    $scope.position_index = [];

                    $scope.$on('position.index', function(event, data) {
                        $scope.position_index = data;
                    });

                    $scope.$on('position.create', function(event, data) {
                        $rootScope.send('position.index', {});
                        $state.go("^");
                    });

                    $scope.$on('position.destroy', function(event, data) {
                        $scope.position_index =
                            _.filter($scope.position_index,
                                     function(e) { return e.id != data.id; });
                    });
                }
            })
            .state("setting.organ.position.create", {
                url: "/create",
                templateUrl: "/static/partial/setting/organ/position/create.html",
                params: {id: true, name: true, member: true},
                controller: function($scope, $state) {
                    $scope.position_new = $state.params;
                }
            })


        // --------------------------------------------------------------------------------
        // 组织机构 ———— 岗位设置
        // --------------------------------------------------------------------------------
            .state("setting.job", {
                url: "/job",
                templateUrl: "/static/partial/setting/job/index.html",
                controller: function($rootScope, $scope, $state) {
                    $rootScope.cloap.admin_module.current = 'job';

                    $scope.refs = {
                        user_index:     [], user_hash:     {},
                        organ_index:    [], organ_hash:    {},
                        position_index: [], position_hash: {}
                    };

                    $scope.user_job = function(organ, user) {
                        var jobs = _.where($scope.job_index, {organ: organ});
                        var result =  _.filter(jobs, function(e) { return _.contains(e.assign, user); });
                        return result;
                    };

                    $scope.$on('user.index', function(event, data) {
                        $scope.refs.user_index = data;
                        $scope.refs.user_hash = _.indexBy(data, 'dn');
                    });

                    $scope.$on('organ.index', function(event, data) {
                        $scope.refs.organ_index = data;
                        $scope.refs.organ_hash = _.indexBy(data, 'dn');
                    });

                    $scope.$on('position.index', function(event, data) {
                        $scope.refs.position_index = data;
                        $scope.refs.position_hash = _.indexBy(data, 'dn');
                    });

                    $scope.job_index = [];
                    $scope.$on('job.index', function(event, data) {
                        $scope.job_index = data;
                    });

                    $scope.$on('job.create', function(event, data) {
                        $scope.job_index =
                            _.filter($scope.job_index,
                                     function(e) { return e.id != data.id; });
                        $scope.job_index.push(data);
                    });

                    $scope.$on('job.edit', function(event, data) {
                        $scope.job_index =
                            _.filter($scope.job_index,
                                     function(e) { return e.id != data.id; });
                        $scope.job_index.push(data);
                        $state.go("^");
                    });


                    $scope.$on('job.destroy', function(event, data) {
                        $scope.job_index =
                            _.filter($scope.job_index,
                                     function(e) { return e.id != data.id; });
                    });
                }
            })
            .state("setting.job.edit_subject", {
                url: "/edit_subject",
                templateUrl: "/static/partial/setting/job/edit_subject.html",
                params: {organ: true, assign: true, jobs: true},
                controller: function($rootScope, $scope, $state) {
                    $scope.member = $state.params;
                    $scope.member.subjects = _.map($scope.member.jobs, function(e) { return e.subject; });

                    $scope.send_command = function(value) {
                        _.each(value.subjects, function(e) {
                            var found = _.find(value.jobs, function(sub) {return sub.subject == e;});
                            if (found == undefined) {
                                $rootScope.send('job.create',
                                                {organ: value.organ.dn, subject: e, assign: [value.assign.dn], mode: 'append'});
                            };
                        });
                        _.each(value.jobs, function(e) {
                            var found = _.find(value.subjects, function(sub) {return sub == e.subject;});
                            if (found == undefined) {
                                $rootScope.send('job.create',
                                                {organ: value.organ.dn, subject: e.subject, assign: [value.assign.dn], mode: 'delete'});
                            };
                        });
                        $state.go("^");
                    };

                    $scope.toggle_selection = function(dn) {
                        var idx = $scope.member.subjects.indexOf(dn);
                        if (idx > -1) {
                            $scope.member.subjects.splice(idx, 1);
                        }
                        else {
                            $scope.member.subjects.push(dn);
                        }
                    };
                }
            })
            .state("setting.job.create", {
                url: "/create",
                templateUrl: "/static/partial/setting/job/create.html",
                params: {id: true, organ: true, subject: true, assign: true},
                controller: function($rootScope, $scope, $state) {
                    $scope.job_new = $state.params;
                    if ($scope.job_new.id == undefined) {
                        $scope.command = 'job.create';
                    }
                    else {
                        $scope.command = 'job.edit';
                    };

                    if ($scope.job_new.assign == undefined) {
                        $scope.job_new.assign = [];
                    };

                    $scope.toggle_selection = function(dn) {
                        var idx = $scope.job_new.assign.indexOf(dn);
                        if (idx > -1) {
                            $scope.job_new.assign.splice(idx, 1);
                        }
                        else {
                            $scope.job_new.assign.push(dn);
                        }
                    };
                }
            })





            .state("setting.user", {
                url: "/user",
                templateUrl: "/static/partial/setting/user/index.html",
                controller: function($rootScope, $scope, $state) {
                    $rootScope.cloap.admin_module.current = 'user';

                    $scope.user_index = [];
                    $scope.$on('user.index', function(event, data) {
                        $scope.user_index = data;
                    });


                    $scope.$on('user.create', function(event, data) {
                        $scope.user_index.push(data);
                        $state.go("^");
                    });

                    $scope.$on('user.edit', function(event, data) {
                        $scope.user_index = _.map(
                            $scope.user_index,
                            function(x) {
                                return ((x.login == data.login) ? data : x);
                            });
                        $state.go("^");
                    });

                    $scope.$on('user.reset.password', function(event, data) {
                        $state.go("^");
                    });

                    $scope.$on('user.destroy', function(event, data) {
                        if (data.result == "ok") {
                            $scope.user_index = _.filter($scope.user_index,
                                                         function(e) { return data.id !== e.login; });
                        };
                    });
                }
            })
            .state("setting.user.create", {
                url: "/create",
                templateUrl: "/static/partial/setting/user/create.html",
                controller: function($scope) {
                    $scope.user_new = {};
                }
            })
            .state("setting.user.edit", {
                url: "/edit",
                templateUrl: "/static/partial/setting/user/edit.html",
                params: {login: true, name: true, password: true, mail: true, mobile: true},
                controller: function($scope, $state) {
                    $scope.user_new = $state.params;
                }
            })
            .state("setting.user.reset_passwd", {
                url: "/reset_passwd",
                templateUrl: "/static/partial/setting/user/reset_passwd.html",
                params: {login: true, name: true, password: true, mail: true, mobile: true},
                controller: function($scope, $state) {
                    $scope.user_new = $state.params;
                }
            })
    })
    .filter("valid_state", function() {
        return function(state) {
            if (state) {return "有效";};
            return "无效";
        };
    });
